package com.bing.picture;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import static com.bing.util.AssertUtils.notBlank;

public class InternetPicture extends AbastractPicture {
	
	public InternetPicture(String pictureUrl) {
		this(pictureUrl, pictureUrl);
	}

	public InternetPicture(String pictureUrl, String pk) {
		super(new InternetPictureStream().stream(pictureUrl), pk);
		this.pictureUrl = pictureUrl;
	}

	@Override
	public String name() {

		String realUrl = this.pictureUrl;
		if (this.pictureUrl.contains("?")) {
			realUrl = pictureUrl.split("?")[0];
		}
		int index = realUrl.lastIndexOf("/");
		return this.name = realUrl.substring(index, realUrl.length() - 1);
	}

	static class InternetPictureStream implements PictureStream {
		
		private InternetPictureStream() {
		}

		@Override
		public InputStream stream(String pictureUrl) {

			notBlank(pictureUrl, "picture url must not be blank!");
			URL url = null;
			InputStream inputStream = null;
			try {
				url = new URL(pictureUrl);
				inputStream = url.openStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return inputStream;
		}
	}

}
